package com.hy.mvc.web.conroller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.hy.mvc.biz.service.common.support.UserContext;
import com.hy.mvc.biz.service.manager.base.JedisCacheManager;
import com.hy.mvc.domain.dataobject.VerifyCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <pre>
 *    author  : Booker
 *    time    : 2017/12/29 15:14
 *    desc    : show the function of this class
 *    version : v1.0
 * </pre>
 */

@Api(value = "验证码API")
@Controller
public class CaptcaController extends BaseController {

    protected Logger logger = LoggerFactory.getLogger(CaptcaController.class);
    @Autowired
    private Producer producer;

    @Resource
    private JedisCacheManager jedisCacheManager;

    @RequestMapping(value = "/vcode/generate", method = RequestMethod.GET)
    @ApiOperation("生成验证码")
    public String gennerate(HttpServletRequest request, HttpServletResponse response) {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        //生成验证码文字
        String validateText = producer.createText();
        UserContext.current().setVCode(validateText);
        request.setAttribute("vcode", validateText);
        //存储到session中
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, validateText);

        BufferedImage bImage = producer.createImage(validateText);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(bImage, "jpg", outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 校验验证码
     *
     * @return 返回是否校验成功
     */
    @RequestMapping(value = "/user/user/checkVerifyCode.json", method = {RequestMethod.POST})
    @ApiOperation("验证验证码")
    public @ResponseBody
    Map<String, String> check(@RequestBody VerifyCode verifyCode, HttpServletRequest request) {
        HttpSession session = request.getSession();
        Map<String, String> result = new HashMap<>();

        //session中的验证码
        String codeFromSession = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        //使用之后删除
        session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);

        if (StringUtils.isNotBlank(verifyCode.getVerifyCodeValue()) && StringUtils.isNotBlank(codeFromSession)) {
            if (verifyCode.getVerifyCodeValue().equalsIgnoreCase(codeFromSession)) {
                //设置校验成功标志
                session.setAttribute("codeCheck", true);
                result.put("result", "ok");
            } else {
                result.put("result", "error");
            }
        } else {
            result.put("result", "error");
        }
        return result;
    }
}
